<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>聊天室</title>
    <script src="../static/js/jquery.min.js" th:src="@{/static/js/jquery.min.js}"></script>
    <script src="../static/js/canvi.js" th:src="@{/static/js/canvi.js}"></script>
    <script src="../static/js/layui.all.js" th:src="@{/static/js/layui.all.js}"></script>
    <link rel="stylesheet" type="text/css" href="../static/css/demo.css" th:href="@{/static/css/demo.css}" />
    <link rel="stylesheet" type="text/css" href="../static/css/normalize.css" th:href="@{/static/css/normalize.css}"/>
    <link rel="stylesheet" type="text/css" href="../static/css/canvi.css" th:href="@{/static/css/canvi.css}" />
    <link rel="stylesheet" type="text/css" href="../static/css/login.css" th:href="@{/static/css/login.css}"/>
    <link rel="stylesheet" type="text/css" href="../static/css/layui.css" th:href="@{/static/css/layui.css}"/>
    <link rel="stylesheet" href="../static/css/main_common.css" th:href="@{/static/css/main_common.css}"/>
    <link rel="stylesheet" href="../static/css/main.css" th:href="@{/static/css/main.css}"/>
    <!--the css for jquery.mCustomScrollbar-->
    <link rel="stylesheet" href="../static/css/jquery.mCustomScrollbar.min.css" th:href="@{/static/css/jquery.mCustomScrollbar.min.css}"/>
    <!--the css for this plugin-->
    <link rel="stylesheet" href="../static/css/jquery.emoji.css" th:href="@{/static/css/jquery.emoji.css}"/>
    <!--(Optional) the js for jquery.mCustomScrollbar's addon-->
    <script src="../static/js/jquery.mousewheel-3.0.6.min.js" th:src="@{/static/js/jquery.mousewheel-3.0.6.min.js}"></script>
    <!--the js for jquery.mCustomScrollbar-->
    <script src="../static/js/jquery.mCustomScrollbar.min.js" th:src="@{/static/js/jquery.mCustomScrollbar.min.js}"></script>
    <!--the js for this plugin-->
    <script src="../static/js/jquery.emoji.js" th:src="@{/static/js/jquery.emoji.js}"></script>
    <!--vue-->
    <script src="../static/js/vue.min.js" th:src="@{/static/js/vue.min.js}"></script>
    <!--引入变量-->
    <script src="../static/js/common.variate.js"th:src="@{/static/js/common.variate.js}"></script>
    <script src="../static/js/Chat.js"th:src="@{/static/js/Chat.js}"></script>
    <script src="../static/js/me.js" th:src="@{/static/js/me.js}"></script>
    <link rel="stylesheet" type="text/css" href="../static/css/csshake.min.css" th:href="@{/static/css/csshake.min.css}">

</head>

<body onload="checkNotification()" style="background-color: rgb(230, 230, 230)">
    <aside id="aside" class="myCanvasNav canvi-navbar" data-position="left" data-push-content="false" style="width: 100vw;" inert="" aria-hidden="false">
        <div id="canvi" class="canvi-user-info" style="padding-top: 20px;padding-bottom: 20px;">
            <div class="canvi-user-info__data">
                <span id="activeRoom" class="canvi-user-info__title" th:text="'房间号:'+${roomName}">房间号:</span>
                <a id="activeUser" class="canvi-user-info__meta" th:text="'昵称:'+${nickName}">开心畅聊每一天😘</a><br>
                <a id="activePwd" class="canvi-user-info__meta"></a>
            </div>
            <div v-bind:title="msgSwitchTips" class="canvi-user-info__close" onclick="silence()">
                <img id="mute" src="../static/icon/unmute.png" th:src="@{/static/icon/unmute.png}" style="width: 25px;">
            </div>
        </div>
        <ul id="cebian" class="canvi-navigation">
        </ul>
    </aside>

    <main class="js-canvi-content canvi-content"></main>

    <div>
        <button id="btn" style="display: none" class="js-canvi-open-button--left btn">查看在线人数</button>
        <div style="display: none;">
            <div>
                <span>昵称：</span>
                <input id="nick" type="text">
            </div>
            <div>
                <span>房间：</span>
                <input id="room" type="text">
            </div>
            <div>
                <span>用户ID：</span>
                <input id="userId" type="text">
            </div>
        </div>

        <div id="message" style="display: none"></div>

        <div id="footer" class="footer">
            <div id="toolbar" style="padding: 5px;">
                <img id="emoji" v-bind:title="emojiTips" src="/static/icon/emoji.png" style="width: 26px;margin-left: 10px">
                <img id="sendImg" v-bind:title="pictureTips" onclick="moniSendImg()" src="icon/picture.png" th:src="@{/static/icon/picture.png}" style="width: 23px;margin-left: 10px">
                <img id="shakeMsg" v-bind:title="shakeTips" class="shake-constant shake-constant--hover" onclick="vedioStart()" src="icon/shakeFalse.png" th:src="@{/static/icon/shakeFalse.png}" style="width: 22px;margin-left: 10px">
                <img id="clear" v-bind:title="clearTips" onclick="emptyScreen()"src="icon/clear.png" th:src="@{/static/icon/clear.png}" style="width: 23px;margin-left: 10px">
                <img id="send" v-bind:title="sendTips" onclick="send()" src="icon/send.png" th:src="@{/static/icon/send.png}" style="width: 24px;position: absolute;right: 10px">
            </div>
            <div id="text" contenteditable="true"></div>
        </div>

        <form id="imageUp" style="display: none">
            <a href='javascript:void(0);' class="blueButton">发图</a>
            <input type="file" class="myFileUpload" name="file" id="image" onchange="sendImg(this)"/>
        </form>
    </div>


</body>

<script type="text/javascript" th:inline="javascript">

    var rid = 'tester';
    var uid = new Date().getMilliseconds();
    var recordedVideo = document.querySelector('video#recorded');
    // var loginButton = document.querySelector('button#login');
    // var stopButton = document.querySelector('button#stop');
    var wsHeader;
    var mediaRecorder;

    window.onload=init;

    window.onfocus = function() {
        focus = false;
    };
    window.onblur = function() {
        focus = true;
    };
    // for IE
    document.onfocusin = function() {
        focus = false;
    };
    document.onfocusout = function() {
        focus = true;
    };

    var auth=[[${nickName}]];
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket(wsHost);
    }else{
        layer.msg(unSupportWsMsg,{anim: 6})
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        layer.msg(onerrorMsg,{anim: 6});
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        layer.msg("开始聊天",{anim: 6})
        var roomID = [[${roomName}]];
        var senderId = [[${nickName}]];
        var chatMsg=new Chat.ChatMsg(senderId,roomID,null);
        var dataContent=new Chat.DataContent(Chat.CONNECT,chatMsg);
        websocket.send(JSON.stringify(dataContent));
        self.setInterval("ping()",55000);
    }

    // 鼠标悬停在某些按钮上时延迟Tips
    function delayTips(tips,obj,style,time){
        timer = setTimeout(messagebox,time==null?700:time,tips,obj,style)
    }

    // 停止延迟Tips的计时器
    function stopTimer(){
        if(timer != null){
            clearTimeout(timer);
            layer.closeAll('tips');
        }
    }

    // Tips
    function messagebox(tips,obj,style){
        layer.tips(tips,obj,style);
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        var data = JSON.parse(event.data)
        var msg = data.chatMsg.msg;
        var nick = data.chatMsg.senderId;
        if (focus && mute%2==0) {
            playSound();
            notifyMe(data);
        }
        switch(data.action){
            case 1://第一次(或重连)初始化连接
                getOnlion(data.chatMsg.roomID);
                //layer.msg(123);
                break;
            case 2://聊天消息
                setMessageInnerHTML(nick,text2Emoji2(msg),"");
                break;
            case 5://聊天消息为图片
                alert(Chat.imgServerUrl+msg);
                setImgInnerHTML(nick,Chat.imgServerUrl+msg);
                break;
            case 6://聊天消息为图片
                this.
                break;
            default:
                break;
        }
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        layer.alert(oncloseMsg, {icon: 2});
        var roomID = [[${roomName}]];
        var senderId = [[${nickName}]];
        console.log("1111");
        var chatMsg=new Chat.ChatMsg(senderId,roomID,null);
        var dataContent=new Chat.DataContent(Chat.BREAK,chatMsg);
        websocket.send(JSON.stringify(dataContent));
        console.log(roomID);
        console.log(senderId);
        $("#footer").animate({bottom:'-200px'},400);
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(nick,msg,shake){
        var a = '<div class="botui-message-left"><div ondblclick="stopShake(this)" class="botui-message-content shake-constant shake-constant--hover';
        if (shake != null || shake != ""){
            a = a + ' '+shake+'">';
        }else {
            a = a + '">';
        }
        $("#message").append("<div class='sendUser'><b>"+nick+"</b></div>"+a+msg+b);
        scrollToEnd();
        $(".botui-message-content").animate({'margin-left':'0px'},200);
    }

    //将自己发的消息显示在网页上
    function setMessageInnerHTML2(nick,msg,shake){
        var c = '<div class="botui-message-right"><div ondblclick="stopShake(this)" class="botui-message-content2 shake-constant shake-constant--hover';
        if (shake != null || shake != ""){
            c = c + ' '+shake+'">';
        }else {
            c = c + '">';
        }
        $("#message").append("<div class='sendUser' style='text-align: right;'><b>"+nick+"</b></div>"+c+msg+b);
        scrollToEnd();
        $(".botui-message-content2").animate({'margin-right':'0px'},200);
    }

    //将图片显示在网页上
    function setImgInnerHTML(nick,msg){
        $("#message").append("<div class='sendUser'><b>"+nick+"</b></div>"+aa+"<img style=\"max-width: -moz-available;\" src='"+msg+"'"+b);
        scrollToEnd();
        $(".botui-message-content-img").animate({'margin-left':'0px'},200);
    }

    //将自己发的图片显示在网页上
    function setImgInnerHTML2(nick,msg){
        $("#message").append("<div class='sendUser' style='text-align: right;'><b>"+nick+"</b></div>"+cc+"<img style=\"max-width: -moz-available;\" src='"+msg+"'"+b);
        scrollToEnd();
        $(".botui-message-content2-img").animate({'margin-right':'0px'},200);
    }

    function moniSendImg() {
        document.getElementById("image").click();
    }
    
    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var roomID = [[${roomName}]];
        var senderId = [[${nickName}]];
        var msgBak = document.getElementById('text').innerHTML;
        var nick = document.getElementById('nick').value;
        // 转换emoji
        $($("#text").children(".emoji_icon")).each(function () {
            $(this).prop('outerHTML', textHead+$(this).attr("src").split(emojiPath)[1]+textFoot);
        });
        var msg = document.getElementById('text').innerHTML;
        if (msg != null && msg != ""){
            msg = msg.replace(/"/g,"'");
            var chatMsg=new Chat.ChatMsg(senderId,roomID,msg);
            var dataContent=new Chat.DataContent(Chat.CHAT,chatMsg);
            var data=JSON.stringify(dataContent);
            if (data.length < 8000){
                websocket.send(data);
                document.getElementById('text').innerHTML = null;
                setMessageInnerHTML2(nick,text2Emoji2(msg),shakeList[shakeNum]);
            }else {
                $("#text").html(msgBak);
                layer.msg("文本太长了，少写一点吧😭",{anim: 6});
            }
        }else {
            layer.msg("发空消息是什么意思呢？🤔",{anim: 6});
        }
    }

    //服务端如果用nginx做转发,可能会因'proxy_read_timeout'配置的过短而自动断开连接,默认是一分钟,所以发送心跳连接,保证不聊天的状态下不会断开
    function ping() {
        var roomID = [[${roomName}]];
        var senderId = [[${nickName}]];
        var chatMsg=new Chat.ChatMsg(senderId,roomID,null);
        var dataContent=new Chat.DataContent(Chat.KEEPALIVE,chatMsg);
        websocket.send(JSON.stringify(dataContent));
    }

    // 将文本转换回emoji图片
    function text2Emoji2(emojiMsg) {
        return emojiMsg.replace(new RegExp(textHead,"g"),emojiHead).replace(new RegExp(textFoot,"g"),emojiFoot);
    }

    function init(){

        $('#btn').trigger("click");
        getOnlion(document.getElementById('room').value);
        $("#window").animate({top:'-100%'},500);
        $("#footer").animate({bottom:'0px'},400);
        $("#message").show();
        layer.alert(firstTips);
        //因为该方法会引起较近的动画卡顿，所以让他先老实一会儿
        setTimeout(function(){ loadEmoji(); }, 500);
    }

    // 加载表情，这个方法需要一定时间，因此可能造成肉眼可见的卡顿
    function loadEmoji() {
        $("#text").emoji({
            button: "#emoji",
            showTab: true,
            animation: 'slide',
            icons: [{
                name: "QQ表情",
                path: "/static/dist/img/qq/",
                maxNum: 154,
                file: ".gif"

            },{
                name: "贴吧表情",
                path: "/static/dist/img/tieba/",
                maxNum: 50,
                file: ".jpg"
            },{
                name: "dog",
                path: "/static/dist/img/dog/",
                maxNum: 37,
                file: ".png"
            },{
                name: "坏坏",
                path: "/static/dist/img/huai/",
                maxNum: 189,
                file: ".png"
            },{
                name: "坏坏GIF",
                path: "/static/dist/img/huaiGif/",
                maxNum: 26,
                file: ".gif"
            },{
                name: "微博",
                path: "/static/dist/img/weibo/",
                maxNum: 93,
                file: ".png"
            },{
                name: "猥琐萌",
                path: "/static/dist/img/xiaoren/",
                maxNum: 186,
                file: ".gif"
            }]
        });
    }

    //监听按键
    $(document).keydown(function(e) {
        // 回车键发送消息
        if (e.keyCode == 13) {
            var topValue = $("#window").css('top');
            var topPx = topValue.substring(0,topValue.length-2);
            if (topPx > 0){
                editNick();
            }else {
                send();
                return false;
            }
        }else if(e.keyCode == 27){ //Esc键关闭抖动消息
            $('#shakeMsg').attr("src","../static/icon/shakeFalse.png");
            $("#shakeMsg").removeClass(shakeList[shakeNum]);
            shakeNum=0;
            layer.msg("抖动消息已关闭");
        }
    });

    //发送消息后自动滚到底部
    function scrollToEnd(){
        var h = $("html,body").height()-$(window).height();
        $("html,body").animate({scrollTop:h},200);
    }


    //获得当前房间中的所有用户
    function getOnlion(room) {
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:8010/online",
            data: {room:room},
            dataType: "json",
            success: function(data){
                if (data.onlineNum > 0){
                    //alert(data.onlineNum);
                    var onlineUsera = data.users;
                    $("#cebian").html("");
                    onlineUsera.forEach(function (user) {
                        var color = "#00ce46";
                        if (shieldMap.has("user-"+user)){
                            color = "#FF3A43"
                        }
                        if(user==auth){
                            var html = '<li>\n' +
                                '                <a class="canvi-navigation__item">\n' +
                                '                    <span title="点击屏蔽此人，不让其接收自己的消息" id="user-'+user+'" class="canvi-navigation__icon-wrapper" onclick="shield(this)" style="background: '+color+';">\n' +
                                '                        <span class="canvi-navigation__icon icon-iconmonstr-code-13"></span>\n' +
                                '                    </span>\n' +
                                '                    <span class="canvi-navigation__text">'+user+'</span>\n' +
                                '                </a>\n' +
                                '                <div id="vedio" style="">\n' +
                                '                  <!--在当前页面显示视频-->\n' +
                                '                  <video id="recorded" autoplay muted></video>\n' +
                                '                  <strong id="self'+user+'"></strong>\n' +
                                '                 </div>\n'
                            '            </li>';
                        }else {
                            var html = '<li>\n' +
                                '                <a class="canvi-navigation__item">\n' +
                                '                    <span title="点击屏蔽此人，不让其接收自己的消息" id="user-' + user + '" class="canvi-navigation__icon-wrapper" onclick="shield(this)" style="background: ' + color + ';">\n' +
                                '                        <span class="canvi-navigation__icon icon-iconmonstr-code-13"></span>\n' +
                                '                    </span>\n' +
                                '                    <span class="canvi-navigation__text">' + user + '</span>\n' +
                                '                </a>\n' +
                                '                <div id="vedio" style="display: none">\n' +
                                '                  <!--在当前页面显示视频-->\n' +
                                '                  <video id="others-' + user + '" autoplay muted></video>\n' +
                                '                  <strong id="self-' + user + '"></strong>\n' +
                                '                 </div>\n'
                            '            </li>';
                        }
                            $("#cebian").append(html);
                    });
                }
            }
        });
    }

    // 屏蔽某个成员不让他接收我的消息
    function shield(obj) {
        var userId = obj.id.substring(5)
        if (userId != $("#userId").val()){
            if (shieldMap.has(obj.id)){
                shieldMap.delete(obj.id);
                layer.msg('该用户将会重新接收到您的消息😁');
            }else {
                shieldMap.set(obj.id,userId);
                layer.msg('该用户将不会接收到您的消息了😉');
            }
            getOnlion(document.getElementById('room').value);
        }else {
            layer.msg('这个是您自己呦，点了也没用😂');
        }
    }

    //播放提示音
    function playSound(){
        var borswer = window.navigator.userAgent.toLowerCase();
        if ( borswer.indexOf( "ie" ) >= 0 )
        {
            //IE内核浏览器
            var strEmbed = '<embed name="embedPlay" src="/static/audio/ding.mp3" autostart="true" hidden="true" loop="false"></embed>';
            if ( $( "body" ).find( "embed" ).length <= 0 )
                $( "body" ).append( strEmbed );
            var embed = document.embedPlay;

            //浏览器不支持 audion，则使用 embed 播放
            embed.volume = 100;
            //embed.play();
        } else
        {
            //非IE内核浏览器
            var strAudio = "<audio id='audioPlay' src='../static/audio/ding.mp3' hidden='true'>";
            if ( $( "body" ).find( "audio" ).length <= 0 )
                $( "body" ).append( strAudio );
            var audio = document.getElementById( "audioPlay" );

            //浏览器支持 audion
            audio.play();
        }
    }


    var t = new Canvi({
        content: ".js-canvi-content",
        isDebug: !1,
        navbar: ".myCanvasNav",
        openButton: ".js-canvi-open-button--left",
        position: "left",
        pushContent: !1,
        speed: "0.2s",
        width: "100vw",
        responsiveWidths: [ {
            breakpoint: "600px",
            width: "21%"
        }, {
            breakpoint: "1280px",
            width: "21%"
        }, {
            breakpoint: "1600px",
            width: "21%"
        } ]
    })


    function sendImg(obj) {
        var file = document.getElementById("imageUp");
        var image = document.getElementById("image");
        if (!(image.value == null || image.value == "")){
            var img = getObjectURL(obj.files[0]);
            var nick = document.getElementById('nick').value;
            setImgInnerHTML2(nick,img);
            var form = new FormData(file);
            loadImage(image,1024);
            upImgByLocalApi(form);
            image.value = null;
        }
    }

    //使用系统本身接口上传图片
    function upImgByLocalApi(form) {
        $.ajax({
            url: "http://127.0.0.1:8010/fileUpload",
            type: "POST",
            data: form,
            async:false,
            processData:false,
            contentType:false,
            success: function (data) {
                if (data.code==0){
                    var roomID = [[${roomName}]];
                    var senderId = [[${nickName}]];
                    var chatMsg=new Chat.ChatMsg(senderId,roomID,data.data);
                    var dataContent=new Chat.DataContent(Chat.IMAGE,chatMsg);
                    var data=JSON.stringify(dataContent);
                    websocket.send(data);
                }
            },
            error: function (data) {
                layer.msg("失败",{anim: 6});
            }
        });
    }

    function silence() {
        mute++;
        if (mute%2 == 0){
            $('#mute').attr("src","/static/icon/unmute.png");
            layer.msg("消息通知已开启");
        }else {
            $('#mute').attr("src","/static/icon/mute.png");
            layer.msg("消息通知已关闭");
        }
    }


    new Vue({
            el: '#toolbar',
            data: {
                emojiTips : emojiTips,
                pictureTips : pictureTips,
                shakeTips : shakeTips,
                clearTips : clearTips,
                sendTips : sendTips,
            }
        })

    new Vue({
        el: '#canvi',
        data: {
            msgSwitchTips : msgSwitchTips
        }
    })


    //=========================================视频模块==============



    function vedioInit() {
        rid = 'tester';
        uid = new Date().getMilliseconds();
        recordedVideo = document.querySelector('video#recorded');
        //获取音视频文件
        var constraints = {
            audio: true,
            //video: true
            //min:表示最小分辨率，ideal表示理想值，max：表示最大值
            video: {width: {min: 640, ideal: 640, max: 640}, height: {min: 480, ideal: 480, max: 480}}
        };
        //初始化，then和catch是并列关系，因为是链式操作
        navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);

        //通道选择，处于安全考虑，远程使用https,localhost使用http
        wsHeader = 'ws://';
        if (location.protocol === 'https:') wsHeader = 'wss://';
    }

    //返回流对象，需要后续的MediaRecorder封装后才能处理
    function handleSuccess(stream) {
        log('getUserMedia() got stream: ', stream);
        //stream即为返回成功的结果，设置为全局便于的后续上传操作
        window.stream = stream;
        //显示在页面上
        recordedVideo.srcObject = stream;
        recordedVideo.onloadedmetadata = function (e) {
            log("Label: " + stream.label);
            //音轨，PCM
            log("AudioTracks", stream.getAudioTracks());
            //视频图像
            log("VideoTracks", stream.getVideoTracks());
            create();
        };
    }

    //处理错误信息
    function handleError(error) {
        console.log('navigator.getUserMedia error: ', error.message, error.stack);
        var msg = JSON.stringify(error);
        alert('navigator.getUserMedia error: message ' + error.message);
        alert('navigator.getUserMedia error: stack ' + error.stack);
        log('navigator.getUserMedia error: ' + error)
    }

    //基于浏览器的安全策略，通过WebRTC（具体为getUserMedia）调用摄像头和麦克风获取音视频数据，
    // 只能是在HTTPS下的网页，或者是本地localhost下才能调用，需要先校验。
    function validate() {
        var isSecureOrigin = location.protocol === 'https:' ||
            location.hostname === '127.0.0.1';
        if (!isSecureOrigin) {
            alert('getUserMedia() must be run from a secure origin: HTTPS or localhost.' +
                '\n\nChanging protocol to HTTPS');
            location.protocol = 'HTTPS';
        }
    }

    //进行注册，也就是初始化===================================
    function vedioStart() {
        vedioInit();
        $('#vedio').css('display','inline');
        validate();
        startRecording();
    }

    function create() {
        document.getElementById('con').innerHTML = 'mimeType ' + mimeType;
        try {
            var options = {mimeType: mimeType};
            mediaRecorder = new MediaRecorder(window.stream, options);
        } catch (e) {
            console.error('Exception while creating MediaRecorder: ' + e);
            log('Exception while creating MediaRecorder: ' + e);
            alert('Exception while creating MediaRecorder: '
                + e + '. mimeType: ' + options.mimeType);
            console.log('Exception while creating MediaRecorder: ');
            return;
        }
        log('Created MediaRecorder', mediaRecorder, 'with options', options);
        mediaRecorder.onstop = handleStop;
        mediaRecorder.ondataavailable = handleDataAvailable;
    }

    function startRecording() {
        //开始录制，最好设置录制的间隔参数，1000代表的是每1000毫秒调用handleDataAvailable处理音视频数据，
        // 我们可以通过handleDataAvailable间接上传数据。
        mediaRecorder.start(1000);
        console.log('MediaRecorder started', mediaRecorder);
    }

    //停止录制
    function stopRecording() {
        mediaRecorder.stop();
        console.log('Recorded Blobs: ', recordedBlobs);
    }

    var recordedBlobs = [];
    var transferBlobs = [];
    var isQuick = true;
    var forIndex = 0;
    var lower = 30;
    //设置音视频的编码格式
    var mimeType = 'video/webm; codecs="opus, vp8"';

    //根据mediaRecorder.start(1000)设置的时间会触发一次
    function handleDataAvailable(event) {
        if (event.data && event.data.size > 0) {
            console.log('正在发送数据...');
            recordedBlobs.push(event.data);
            if (isQuick) {
                var str = binaryToStr(event.data);
                var roomID = [[${roomName}]];
                var senderId = [[${nickName}]];
                var chatMsg=new Chat.ChatMsg(senderId,roomID,str);
                var dataContent=new Chat.DataContent(Chat.VEDIO,chatMsg);
                websocket.send(JSON.stringify(dataContent));
            } else {
                //按间隔发送
                transferBlobs.push(event.data);
                forIndex += 1;
                console.log('正在发送数据...'+ forIndex + ' ' + lower);
                if (forIndex > lower) {
                    console.log(getTime() + ' ' + transferBlobs.length);
                    socket.send(new Blob(transferBlobs, {type: mimeType}));
                    transferBlobs = [];
                    forIndex = 0;
                }
            }

        }
    }

    function handleStop(event) {
        console.log('Recorder stopped: ', event);
    }


    function getTime() {
        var date = new Date();
        return date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds();
    }


    let dataConnections = [];


    var showFlag = true;
    var log = function () {
        if (showFlag) {
            console.log.apply(null, arguments);
        }
    }

    class DataConnection {
        constructor(from, to, vid, rid, mimeType) {
            this.dataBlobs = [];
            this.isActive = false;
            this.currentTime = 0;
            this.startIndex = 0;
            this.from = from;
            this.to = to;
            this.vid = vid;
            this.rid = rid;
            this.mineType = mimeType;
            var wsHeader = 'ws://';
            if (location.protocol === 'https:') wsHeader = 'wss://';
            this.dataConnection = new WebSocket(wsHeader + window.location.host +websocket);
            this.dataConnection.binaryType = 'arraybuffer';
            this.dataConnectionOpen = this.dataConnectionOpen.bind(this);
            this.dataConnectionMessage = this.dataConnectionMessage.bind(this);
            this.dataConnectionClose = this.dataConnectionClose.bind(this);
            this.dataConnectionError = this.dataConnectionError.bind(this);
            this.dataConnection.onopen = this.dataConnectionOpen;
            this.dataConnection.onmessage = this.dataConnectionMessage;
            this.dataConnection.onclose = this.dataConnectionClose;
            this.dataConnection.onerror = this.dataConnectionError;

            if (window.MediaSource) {
                this.vidElement = document.getElementById(vid);
                var mediaSource = new MediaSource();
                this.vidElement.src = URL.createObjectURL(mediaSource);
                this.sourceOpen = this.sourceOpen.bind(this);
                this.sourceEnded = this.sourceEnded.bind(this);
                this.sourceClose = this.sourceClose.bind(this);
                mediaSource.addEventListener('sourceopen', this.sourceOpen);
                mediaSource.addEventListener('sourceended', this.sourceEnded);
                mediaSource.addEventListener('sourceclose', this.sourceClose);
            } else {
                console.log("The Media Source Extensions API is not supported.")
            }
        }


        dataConnectionOpen() {
            console.log("连接已经建立。", "connectionId=", this.toString());
        }

        dataConnectionMessage(event) {
            console.log('正在接收数据...', event.data);
            this.dataBlobs.push(event.data);
            if (this.sourceBuffer) {
                this.sourceBuffer.appendBuffer(event.data);
            } else {
                alert('no init sourceBuffer');
            }
            if (!this.isActive) {
                this.isActive = true;
                //document.getElementById(this.vid).click();
            } else {
                this.startIndex += 1;
                this.currentTime += 1;
            }
        }
        dataConnectionClose() {
            console.log("连接关闭。", "ERROR");
        }
        dataConnectionError() {
            console.log("WebSocket错误。", "ERROR");
        }
        //添加sourceBuffer，实际上数据的交互在此对象中。
        //当加载完成后
        sourceOpen(e) {
            console.log('sourceOpen');
            //alert('sourceOpen');
            //节省内存，可不用这句
            URL.revokeObjectURL(this.vidElement.src);
            var mime = this.mineType;
            var mediaSource = e.target;
            //添加解码格式
            this.sourceBuffer = mediaSource.addSourceBuffer(mime);
            this.streamPlay = this.streamPlay.bind(this);
            this.sourceBuffer.addEventListener('updateend', this.streamPlay);
        }

        sourceEnded(e) {
            console.log('sourceEnded');
            //alert('sourceEnded');
        }

        streamPlay(e) {
            var mediaSource = e.target;
            log('...updating ', this.sourceBuffer.updating, '...readyState ', mediaSource.readyState);
            document.getElementById(this.vid).play();
        }

        sourceClose(e) {
            console.log('sourceClose');
        }


        play() {
            console.log(this.dataBlobs);
            var recordedVideo = document.getElementById(this.vid);
            recordedVideo.currentTime = this.currentTime;
            recordedVideo.play();
            recordedVideo.onclick = function () {
                log('new');
            }
            recordedVideo.onended = function () {
                log('onended');
            }
        }

        id() {
            return this.from + '-' + this.to;
        }

        toString() {
            return this.id() + ' by ' + this.vid;
        }
    }
</script>
</html>